package com.ctibook.booksystem.job;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.cti.ftpservice.utils.Base64CoderUtils;
import com.cti.ftpservice.utils.FileHelper;
import com.cti.ftpservice.utils.ZipUtils;
import com.ctibook.booksystem.service.bookcatalog.BookInfoService;
import com.ctibook.booksystem.service.bookcatalog.BookInfoUploadFileRecordService;
import com.ctibook.booksystem.vo.bookcatalog.BookInfoCategoryVO;
import com.ctibook.booksystem.vo.bookcatalog.BookInfoDetailsVO;
import com.ctibook.booksystem.vo.bookcatalog.BookInfoExtendPropVO;
import com.ctibook.booksystem.vo.bookcatalog.BookInfoUploadFileRecordVO;
import com.ctibook.booksystem.vo.bookcatalog.BookInfoExtralVo;
import com.mchange.v2.lang.StringUtils;

/**
 * 将BookInfoVO数据添加到BookInfo
 * 
 * @author 鲁永刚
 * 
 */
@Component("importBookInfo2Job")
@Scope("singleton")
public class ImportBookInfo2Job {
	
	static Logger log = Logger.getLogger(ImportBookInfo2Job.class);
	
	@Resource
	private BookInfoService bookInfoService;
	
	@Resource
	private BookInfoUploadFileRecordService bookInfoUploadFileRecordService;

	public void doWork() {
		log.info("开始保存书目数据");
		List<BookInfoUploadFileRecordVO> records = bookInfoUploadFileRecordService.getRequireHandlerBookInfoUploadFileRecordVos();
		if (records == null || records.size() == 0) {
			log.info("保存书目数据任务执行完成:没有任何上传的文件");
			return;
		}
		for (final BookInfoUploadFileRecordVO vo : records) {
			log.info("开始保存书目数据:"+vo.getFileName());
			handlerFileData(vo);
			log.info("结束保存书目数据:"+vo.getCorrectMarcRecordCount());
		}
		log.info("保存书目数据任务执行完成");
	}

	private void handlerFileData(BookInfoUploadFileRecordVO vo) {
		if(vo.getParsed())
			return;
		vo.setTotalMarcRecordCount(0);
		vo.setCorrectMarcRecordCount(0);
		vo.setIntoDbMarcRecordCount(0);
		String filePath = FilenameUtils.concat(FileHelper.getBaseClassPath(), vo.getFileName());
		File file = new File(filePath);
		if (!file.exists()) {
			// 解析完成，文件不存在
			setErrorMsg(vo, "上传文件丢失");
		} else {
			if (!FilenameUtils.isExtension(vo.getFileName(), "zip")) {
				setErrorMsg(vo, "上传文件不是有效的zip文件");
			} else {
				List<String> zipedFilePaths = null;
				boolean flag = false;
				try {
					zipedFilePaths = ZipUtils.unZip(file.getAbsolutePath());
					flag = true;
				} catch (Exception e) {
					setErrorMsg(vo, "解压zip文件失败：" + e.getMessage());
				}
				if (flag) {
					vo.setParseSuccess(true);
					if (zipedFilePaths != null && zipedFilePaths.size() > 0) {
						for (String xmlFilePath : zipedFilePaths) {
							if (FilenameUtils.isExtension(xmlFilePath, "xml")) {
									File xmlFile = new File(xmlFilePath);
									// 读取文件并解析文件
									try{
										List<BookInfoDetailsVO> books = ParseXmlFile(xmlFile);
										vo.setTotalMarcRecordCount(vo.getTotalMarcRecordCount()+books.size());
										if (books != null && books.size() > 0) {
											// 添加到数据库
											for (BookInfoDetailsVO bookInfoDetailsVO : books) {
												BookInfoDetailsVO decodeBookInfoVo = null;
												String isbn="";
												try {
													decodeBookInfoVo = (BookInfoDetailsVO) Base64CoderUtils.decoderObj2(bookInfoDetailsVO);
													if(decodeBookInfoVo!=null){
														isbn=decodeBookInfoVo.getIsbn();
													}
													vo.setCorrectMarcRecordCount(vo.getCorrectMarcRecordCount()+1);
													bookInfoService.addOrUpdateBookInfoSync(decodeBookInfoVo,vo.isCheckedIsbn());
													vo.setIntoDbMarcRecordCount(vo.getIntoDbMarcRecordCount()+1);
													
												} catch (Exception e) {
													e.printStackTrace();
													log.error("解析数据出错:["+isbn+"]"+e.getCause().getMessage());
		 											vo.setErrorMsg("解析数据出错:["+isbn+"]"+e.getCause().getMessage());
												}
											}
										}
									}catch(Exception ex){
										ex.printStackTrace();
										log.error(ex);
										vo.setErrorMsg("解析数据出错："+ex.getMessage());
									}
							    }
							}
						}
						
					}
				vo.setParsed(true);
			}
		}
		//保存数据
		bookInfoUploadFileRecordService.updateBookInfoUploadFileRecord(vo);
	}
	
	private void setErrorMsg(final BookInfoUploadFileRecordVO vo, String errorMsg) {
		vo.setParsed(true);
		vo.setErrorMsg(errorMsg);
		vo.setParseSuccess(false);
	}

	
	@SuppressWarnings("rawtypes")
	private List<BookInfoDetailsVO> ParseXmlFile(File zipedFile) throws Exception {
		List<BookInfoDetailsVO> books = new ArrayList<BookInfoDetailsVO>();
		SAXReader reader = new SAXReader();
		Document document = reader.read(zipedFile);

		Element rootElement = document.getRootElement();
		List bookElements = rootElement.elements("book");
		for (Iterator iterator = bookElements.iterator(); iterator.hasNext();) {
			Element bookElement = (Element) iterator.next();
			BookInfoDetailsVO vo = new BookInfoDetailsVO();

			// author
			String authorValue = bookElement.element("author").getText();
			authorValue = StringUtils.nonEmptyTrimmedOrNull(authorValue);
			vo.setAuthor(authorValue);

			// binding
			String bindingValue = bookElement.element("binding").getText();
			bindingValue = StringUtils.nonEmptyTrimmedOrNull(bindingValue);
			vo.setBinding(bindingValue);

			// checkApproveUserId
			String checkApproveUserIdValue = bookElement.element("checkApproveUserId").getText();
			checkApproveUserIdValue = StringUtils.nonEmptyTrimmedOrNull(checkApproveUserIdValue);
			vo.setCheckApproveUserId(checkApproveUserIdValue);

			// checkApproveUserName
			String checkApproveUserNameValue = bookElement.element("checkApproveUserName").getText();
			checkApproveUserNameValue = StringUtils.nonEmptyTrimmedOrNull(checkApproveUserNameValue);
			vo.setCheckApproveUserName(checkApproveUserNameValue);

			// chineseTitle
			String chineseTitleValue = bookElement.element("chineseTitle").getText();
			chineseTitleValue = StringUtils.nonEmptyTrimmedOrNull(chineseTitleValue);
			vo.setChineseTitle(chineseTitleValue);
			
			// clcs
			String clcs = bookElement.element("clcs").getText();
			clcs = StringUtils.nonEmptyTrimmedOrNull(clcs);
			vo.setClcs(clcs);

			// createUserId
			String createUserIdValue = bookElement.element("createUserId").getText();
			createUserIdValue = StringUtils.nonEmptyTrimmedOrNull(createUserIdValue);
			vo.setCreateUserId(createUserIdValue);

			// createUserName
			String createUserNameValue = bookElement.element("createUserName").getText();
			createUserNameValue = StringUtils.nonEmptyTrimmedOrNull(createUserNameValue);
			vo.setCreateUserName(createUserNameValue);

			// currency
			String currencyValue = bookElement.element("currency").getText();
			currencyValue = StringUtils.nonEmptyTrimmedOrNull(currencyValue);
			vo.setCurrency(currencyValue);

			
			// edition
			String editionValue = bookElement.element("edition").getText();
			editionValue = StringUtils.nonEmptyTrimmedOrNull(editionValue);
			vo.setEdition(editionValue);

			// isbn
			String isbnValue = bookElement.element("isbn").getText();
			isbnValue = StringUtils.nonEmptyTrimmedOrNull(isbnValue);
			vo.setIsbn(isbnValue);
			
			
			// categoryVos
			String categoryVosValue = bookElement.element("categoryVos").getText();
			categoryVosValue = StringUtils.nonEmptyTrimmedOrNull(categoryVosValue);
			vo.setCategorys(categoryVosValue);
			
			// categoryVo1
			String category1Value = bookElement.element("category1").getText();
			category1Value = StringUtils.nonEmptyTrimmedOrNull(category1Value);
			vo.setCategory1(category1Value);
			
			// categoryVo2
			String category2Value = bookElement.element("category2").getText();
			category2Value = StringUtils.nonEmptyTrimmedOrNull(category2Value);
			vo.setCategory2(category2Value);
						

			// language
			String languageValue = bookElement.element("language").getText();
			languageValue = StringUtils.nonEmptyTrimmedOrNull(languageValue);
			vo.setLanguage(languageValue);

			// pageSize

			String pageSizeSpecifiedValue = bookElement.element("pageSizeSpecified").getText();
			pageSizeSpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(pageSizeSpecifiedValue);
			boolean flagPageSizeSpecifiedValue = Boolean.parseBoolean(pageSizeSpecifiedValue);
			if (flagPageSizeSpecifiedValue) {
				String pageSizeValue = bookElement.element("pageSize").getText();
				pageSizeValue = StringUtils.nonEmptyTrimmedOrNull(pageSizeValue);
				Integer pageSize = Integer.parseInt(pageSizeValue);
				vo.setPageSize(pageSize);
			} else {
				vo.setPageSize(null);
			}

			// price
			String priceSpecifiedValue = bookElement.element("priceSpecified").getText();
			priceSpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(priceSpecifiedValue);
			boolean flagPriceSpecifiedValue = Boolean.parseBoolean(priceSpecifiedValue);
			if (flagPriceSpecifiedValue) {
				String priceValue = bookElement.element("price").getText();
				priceValue = StringUtils.nonEmptyTrimmedOrNull(priceValue);
				Float price = Float.parseFloat(priceValue);
				vo.setPrice(price);
			} else {
				vo.setPrice(null);
			}

			// pubYear
			String pubYearSpecifiedValue = bookElement.element("pubYearSpecified").getText();
			pubYearSpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(pubYearSpecifiedValue);
			boolean flagPubYearSpecifiedValue = Boolean.parseBoolean(pubYearSpecifiedValue);
			if (flagPubYearSpecifiedValue) {
				String pubYearValue = bookElement.element("pubYear").getText();
				pubYearValue = StringUtils.nonEmptyTrimmedOrNull(pubYearValue);
				int pubYear = Integer.parseInt(pubYearValue);
				vo.setPubYear(pubYear);

				String pubMonthSpecifiedValue = bookElement.element("pubMonthSpecified").getText();
				pubMonthSpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(pubMonthSpecifiedValue);
				boolean flagPubMonthSpecifiedValue = Boolean.parseBoolean(pubMonthSpecifiedValue);
				if (flagPubMonthSpecifiedValue) {
					String pubMonthValue = bookElement.element("pubMonth").getText();
					pubMonthValue = StringUtils.nonEmptyTrimmedOrNull(pubMonthValue);
					int pubMonth = Integer.parseInt(pubMonthValue);
					vo.setPubMonth(pubMonth);

					String pubDaySpecifiedValue = bookElement.element("pubDaySpecified").getText();
					pubDaySpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(pubDaySpecifiedValue);
					boolean flagPubDaySpecifiedValue = Boolean.parseBoolean(pubDaySpecifiedValue);
					if (flagPubDaySpecifiedValue) {
						String pubDayValue = bookElement.element("pubDay").getText();
						pubDayValue = StringUtils.nonEmptyTrimmedOrNull(pubDayValue);
						int pubDay = Integer.parseInt(pubDayValue);
						vo.setPubDay(pubDay);
					} else {
						vo.setPubDay(null);
					}

				} else {
					vo.setPubMonth(null);
					vo.setPubDay(null);
				}
			} else {
				vo.setPubYear(null);
				vo.setPubMonth(null);
				vo.setPubDay(null);
			}

			// publisherId
			String publisherIdValue = bookElement.element("publisherId").getText();
			publisherIdValue = StringUtils.nonEmptyTrimmedOrNull(publisherIdValue);
			vo.setPublisherId(publisherIdValue);

			// publisherName
			String publisherNameValue = bookElement.element("publisherName").getText();
			publisherNameValue = StringUtils.nonEmptyTrimmedOrNull(publisherNameValue);
			vo.setPublisherFullName(publisherNameValue);

			

			// seriesTitle
			String seriesTitleValue = bookElement.element("seriesTitle").getText();
			seriesTitleValue = StringUtils.nonEmptyTrimmedOrNull(seriesTitleValue);
			vo.setSeriesTitle(seriesTitleValue);

			// stock
			String stockSpecifiedValue = bookElement.element("stockSpecified").getText();
			stockSpecifiedValue = StringUtils.nonEmptyTrimmedOrNull(stockSpecifiedValue);
			boolean flagStockSpecifiedValue = Boolean.parseBoolean(stockSpecifiedValue);
			if (flagStockSpecifiedValue) {
				String stockValue = bookElement.element("stock").getText();
				stockValue = StringUtils.nonEmptyTrimmedOrNull(stockValue);
				int stock = Integer.parseInt(stockValue);
				vo.setStock(stock);
			} else {
				vo.setStock(null);
			}

			// subTitle
			String subTitleValue = bookElement.element("subTitle").getText();
			subTitleValue = StringUtils.nonEmptyTrimmedOrNull(subTitleValue);
			vo.setSubTitle(subTitleValue);

			// subjectHeadings	
			String subjectHeadingsValue = bookElement.element("subjectHeadings").getText();
			subjectHeadingsValue = StringUtils.nonEmptyTrimmedOrNull(subjectHeadingsValue);
			vo.setSubjectHeadings(subjectHeadingsValue);
			
			// subjectVos	
			String subjectVosValue = bookElement.element("subjectVos").getText();
			subjectVosValue = StringUtils.nonEmptyTrimmedOrNull(subjectVosValue);
			vo.setSubjectVos(subjectVosValue);
			
			// chineseSubjectHeadings
			String chineseSubjectHeadingsValue = bookElement.element("chineseSubjectHeadings").getText();
			chineseSubjectHeadingsValue = StringUtils.nonEmptyTrimmedOrNull(chineseSubjectHeadingsValue);
			vo.setChineseSubjectHeadings(chineseSubjectHeadingsValue);
		
			String bookSize = bookElement.element("bookSize").getText();
			bookSize = StringUtils.nonEmptyTrimmedOrNull(bookSize);
			vo.setBookSize(bookSize);
			
			String bookWeight = bookElement.element("bookWeight").getText();
			bookWeight = StringUtils.nonEmptyTrimmedOrNull(bookWeight);
			vo.setBookWeight(bookWeight);
			
			// title
			String titleValue = bookElement.element("title").getText();
			titleValue = StringUtils.nonEmptyTrimmedOrNull(titleValue);
			vo.setTitle(titleValue);

			// volumn
			String volumnValue = bookElement.element("volumn").getText();
			volumnValue = StringUtils.nonEmptyTrimmedOrNull(volumnValue);
			vo.setVolumn(volumnValue);
			
			// description
			String descriptionValue = bookElement.element("description").getText();
			descriptionValue = StringUtils.nonEmptyTrimmedOrNull(descriptionValue);
			vo.setDescription(descriptionValue);
			
			//bookInfoExtralVo
			Element bookInfoExtralVoElement= bookElement.element("bookInfoExtralVo");
			if(bookInfoExtralVoElement!=null){
				BookInfoExtralVo bookInfoExtralVo=new BookInfoExtralVo();
				
				
				// lccValue
				String lccValue = bookInfoExtralVoElement.element("lcc").getText();
				lccValue = StringUtils.nonEmptyTrimmedOrNull(lccValue);
				bookInfoExtralVo.setLcc(lccValue);
				
				
				// lccValue
				String ddcValue = bookInfoExtralVoElement.element("ddc").getText();
				ddcValue = StringUtils.nonEmptyTrimmedOrNull(ddcValue);
				bookInfoExtralVo.setDdc(ddcValue);

				String bookInfoExtralVoId = bookInfoExtralVoElement.element("id").getText();
				bookInfoExtralVoId = StringUtils.nonEmptyTrimmedOrNull(bookInfoExtralVoId);
				bookInfoExtralVo.setId(bookInfoExtralVoId);
				
				String bookInfoExtralVoisbn = bookInfoExtralVoElement.element("isbn").getText();
				bookInfoExtralVoisbn = StringUtils.nonEmptyTrimmedOrNull(bookInfoExtralVoisbn);
				bookInfoExtralVo.setIsbn(bookInfoExtralVoisbn);
				
				String ebookIsbn = bookInfoExtralVoElement.element("ebookIsbn").getText();
				ebookIsbn = StringUtils.nonEmptyTrimmedOrNull(ebookIsbn);
				bookInfoExtralVo.setEbookIsbn(ebookIsbn);
				
				String bindingIsbn = bookInfoExtralVoElement.element("bindingIsbn").getText();
				bindingIsbn = StringUtils.nonEmptyTrimmedOrNull(bindingIsbn);
				bookInfoExtralVo.setBindingIsbn(bindingIsbn);
				
				String setIsbn = bookInfoExtralVoElement.element("setIsbn").getText();
				setIsbn = StringUtils.nonEmptyTrimmedOrNull(setIsbn);
				bookInfoExtralVo.setSetIsbn(setIsbn);
				
				String previousISBN = bookInfoExtralVoElement.element("previousISBN").getText();
				previousISBN = StringUtils.nonEmptyTrimmedOrNull(previousISBN);
				bookInfoExtralVo.setPreviousISBN(previousISBN);
				
				String authorAffiliation = bookInfoExtralVoElement.element("authorAffiliation").getText();
				authorAffiliation = StringUtils.nonEmptyTrimmedOrNull(authorAffiliation);
				bookInfoExtralVo.setAuthorAffiliation(authorAffiliation);
				
				String libraryCatalog = bookInfoExtralVoElement.element("libraryCatalog").getText();
				libraryCatalog = StringUtils.nonEmptyTrimmedOrNull(libraryCatalog);
				bookInfoExtralVo.setLibraryCatalog(libraryCatalog);
				
				String awards = bookInfoExtralVoElement.element("awards").getText();
				awards = StringUtils.nonEmptyTrimmedOrNull(awards);
				bookInfoExtralVo.setAwards(awards);
				
				String salesStatus = bookInfoExtralVoElement.element("salesStatus").getText();
				salesStatus = StringUtils.nonEmptyTrimmedOrNull(salesStatus);
				bookInfoExtralVo.setSalesStatus(salesStatus);
				
				String usp = bookInfoExtralVoElement.element("usp").getText();
				usp = StringUtils.nonEmptyTrimmedOrNull(usp);
				bookInfoExtralVo.setUsp(usp);
				
				String validityOfCopyright = bookInfoExtralVoElement.element("validityOfCopyright").getText();
				validityOfCopyright = StringUtils.nonEmptyTrimmedOrNull(validityOfCopyright);
				bookInfoExtralVo.setValidityOfCopyright(validityOfCopyright);
				
				String bookType = bookInfoExtralVoElement.element("bookType").getText();
				bookType = StringUtils.nonEmptyTrimmedOrNull(bookType);
				bookInfoExtralVo.setBookType(bookType);
				
				String lcc = bookInfoExtralVoElement.element("lcc").getText();
				lcc = StringUtils.nonEmptyTrimmedOrNull(lcc);
				bookInfoExtralVo.setLcc(lcc);
				
				String ddc = bookInfoExtralVoElement.element("ddc").getText();
				ddc = StringUtils.nonEmptyTrimmedOrNull(ddc);
				bookInfoExtralVo.setDdc(ddc);
				
				// contents
				String contentsValue = bookInfoExtralVoElement.element("contents").getText();
				contentsValue = StringUtils.nonEmptyTrimmedOrNull(contentsValue);
				bookInfoExtralVo.setContents(contentsValue);
				//产品Id
	            String  productId=bookInfoExtralVoElement.element("productId").getText();
	            productId = StringUtils.nonEmptyTrimmedOrNull(productId);
	            bookInfoExtralVo.setProductId(productId);
				
				// readership
				String readershipValue = bookInfoExtralVoElement.element("readership").getText();
				readershipValue = StringUtils.nonEmptyTrimmedOrNull(readershipValue);
				bookInfoExtralVo.setReadership(readershipValue);

				vo.setBookInfoExtralVo(bookInfoExtralVo);
			}

			books.add(vo);
		}
		return books;
	}

}
